<?php

/**
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/17 19:45
 */

namespace App\Models;



use Exception;

class SysRolePermissionsModel extends BaseModel
{
    protected $table = 'info_sys_role_has_permissions';
    public $timestamps = false;


    /**
     * 获取角色权限列表
     * @param $whereArr
     * @param array $columns
     * @return array
     */
    public function getRolePermissionsAll($whereArr, array $columns = ['*']): array
    {
        //初始化参数
        $this->queryModel = null;
        $data = [];

        if (!empty($whereArr)) {
            $this->queryModel = SysRolePermissionsModel::query();

            //拼接where条件sql
            try {
                $this->spliceSQL();
            } catch (Exception $e) {
            }

            $obj = $this->queryModel->select($columns)
                ->get();
            $data = $obj ? $obj->toArray() : [];
        }
        return $data;
    }

    /**
     * 删除
     * @param $where
     * @return mixed
     */
    public function deleteRolePermissions($where){
        if(empty($where))
            return false;
        return self::query()->where($where)->delete();
    }


    /**
     * 新增
     * @param $data
     * @return bool|null
     */
    public function insertRolePermissions($data):? bool
    {
        if(empty($data))
            return false;
        return self::query()->insert($data);
    }

    /**
     * 获取数据
     * @param string $field
     * @param array $id
     * @return array|null
     */
    public function getDataOne(string $field='', array $id=[]):?array
    {
        $res = self::query();

        if (!empty($id)){
            $res->whereIn($field, $id);
        }

        return $res->get()->toArray();
    }

    /**
     * 查询权限表
     * @param $key
     * @param $value
     * @return mixed
     */
    public function userRoleAll($key, $value)
    {
        $res = self::query()
            ->from('info_sys_role_has_permissions as rp')
            ->leftJoin('info_sys_permissions as p', 'p.id', '=', 'rp.permission_id')
            ->selectRaw('p.id, p.permission_name, p.parent_id, p.level, p.tag, p.icon, p.component, p.path, p.path_url, p.title, p.type, p.redirect')
            ->whereIn($key, $value)
            ->orderBy('p.sort', 'asc')
            ->orderBy('p.id', 'asc')
            ->get();

        return $res ? $res->toArray() : [];

    }

}
